package com.student.xujiang.mysmalluse.retrofit2andrxjava2;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.student.xujiang.R;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class NetworkBaseActivity extends AppCompatActivity {

    public ProgressDialog pd;

    public Function<Observable,ObservableSource> composeFunction;

    private final long RETRY_TIMES  =1;  //就是重试的次数

    private boolean showLoading = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network_base);

        init();
    }

    private void init() {
        pd = new ProgressDialog(this);
//如果subscribe不在主线程，那可以在doOnSubscribe后通过subscribeOn指定它所在的线程。
        composeFunction = new Function<Observable, ObservableSource>() {
            @Override
            public ObservableSource apply(@NonNull Observable observable) throws Exception {
                return observable.retry(RETRY_TIMES) //指示Observable遇到错误时重试
                .subscribeOn(Schedulers.io())  //subscribeOn用来指定网络请求所在的线程，这里用IO线程
                        .doOnSubscribe(new Consumer<Disposable>() {  //doOnSubscribe是在事件发送前进行的操作
                            @Override
                            public void accept(@NonNull Disposable disposable) throws Exception {
                                if(NetworkUtil.isNetworkAvailable(NetworkBaseActivity.this)){  //isNetworkAvailable用来检测网络是否是连接的
                                    if(showLoading){
                                        if(pd != null && !pd.isShowing()){
                                            pd.show();

                                        }
                                    }
                                }else{
                                    Toast.makeText(NetworkBaseActivity.this, "网络连接异常，请检查网络", Toast.LENGTH_LONG).show();
                                }

                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread());  //observeOn是用来指定Observer操作的线程
            }
        };
    }

    public void setLoadingFlag(boolean show){  //最后一个showLoading用来设置是否显示进度框
        showLoading = show;
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
    }
}



